<?php

/*
 * 资讯频道广告管理（测试版，时间原因，后期需要重构）
 */
class ZixunadAction extends CommonAction{
    
    /*
     * 广告列表
     */
    public function index(){
        $m = M('zixunad');
        $count = $m->count();
        $p = new Page($count,10);
        $list = $m->limit("$p->firstRow,$p->listRows")->order('id desc')->select();
        $this->assign('list',$list);
        $this->assign('fpage',$p->show());        
        $this->display();
    }
    
    /*
     * 广告增加
     */
    public function add(){
        $m = M('zixunad');
        if(IS_POST){            
            if(false === $m->create()){$this->error($m->getError());}
            if(false === $id = $m->add()){$this->error('添加失败');}
            $this->save_file($_POST['txt'],$id);//存为js文件
            $this->success('添加成功');exit();
        }
        $this->display();
    }
    
    
    /*
     * 广告修改
     */
    public function edit($id){
        $m = M('zixunad');
        if(IS_POST){
            if(false === $m->create()){$this->error($m->getError());}
            if(false === $m->save()){$this->error('修改失败');}
            $this->save_file($_POST['txt'],$_POST['id']);//存为js文件
            $this->success('修改成功');exit();
        }
        $this->assign('list',$m->find($id));
        $this->display();
    }
    
    
    /*
     * 广告删除
     */
    public function del($id){
        $m = M('archive');
        if(false === $m->delete($id)){$this->error('添加失败');}
        $this->success('删除成功');
    }
    
    /*
     * 将字符串另存为JS文件
     */
    protected function save_file($str,$id){
        $adbody = stripcslashes($str);
        $adbody = str_replace('\\', '\\\\',$adbody);
        $adbody = str_replace('"', '\"',$adbody);
        $adbody = str_replace("'", "\'",$adbody);
        $adbody = str_replace("\r", "\\r",$adbody);
        $adbody = str_replace("\n", "\\n",$adbody);
        $adbody = "<!--\r\ndocument.write(\"{$adbody}\");\r\n-->\r\n";
        $file = APP_PATH.'/ad_js/ad_'.$id.'.js';
        file_put_contents($file, $adbody);
    }
    
    
}